// pages/batch/batch.js
var util = require('../../database/data.js');
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    tid: '',
    cit: '',
    cont_num: 2,
    page_num: 0,
    sms_num: 63,
    signaNum: 0,
    showDialog: false,
    showCenterDialog: true,
    showAlert: true,
    sendOrder: false
  },

  //弹窗
  onClickdiaCenterView: function (e) {
    this.setData({
      showCenterDialog: !this.data.showCenterDialog,
      showDialog: !this.data.showDialog
    })
  },

  //数据提交
  onBatchSubmit: function (e) {
    wx.showLoading();
    switch (e.currentTarget.dataset.classid) {
      case '0':
        var contData = this.data.contData;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: 10067,
          cid: contData.cid,
          tid: contData.tid,
          openId: this.data.userId,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: contData.content.replace(/(^\s*)|(\s*$)/g, ""),
        };
        this.submitSendData(api, sendData);
        break;
      case '1':
        var contData = this.data;
        var api = app.globalData.smsbaoApi + '/batch/sapi/createOrder';
        var sendData = {
          appId: 10067,
          cid: '0',
          tid: '0',
          openId: this.data.userId,
          sendPhone: JSON.stringify(this.data.sendPhone),
          sign: this.data.signature.replace(/(^\s*)|(\s*$)/g, ""),
          content: contData.content,
        };
        this.submitSendData(api, sendData);
        break;
    }

  },

  //发送短信到服务器
  submitSendData: function (url, data) {
    let that = this;
    wx.request({
      url: url,
      method: "post",
      data: {
        appId: data.appId,
        cid: data.cid,
        tid: data.tid,
        openId: data.openId,
        phone: data.sendPhone,
        sign: data.sign,
        content: data.content
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        if (res.data.code == '200') {
          setTimeout(function () {
            wx.hideLoading()
          }, 1000)
          that.ProcessingReturnData(res, data);
          that.setData({
            orderId: res.data.data.orderId,
            showAlert: false,
          })

        } else {
          wx.showToast({
            title: '网络超时',
            icon: 'loading',
            duration: 1500
          })
          var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId';
          that.getUserOpenId(getOpenid);
        }

      },
      fail: function (error) {
        console.log(error)
      }
    })
  },
  //接受返回数据生成订单
  ProcessingReturnData: function (orderId, data) {
    // 调用函数时，传入new Date()参数，返回值是日期和时间  
    var time = util.formatTime(new Date());
    var orderId = orderId.data.data.orderId;
    var orderData = wx.getStorageSync("order");
    var orderInfoData = [];
    for (var i in orderData) {
      orderInfoData.push(orderData[i])
    }
    var orderInfo = {
      orderId: orderId,
      tid: data.tid,
      cid: data.cid,
      phone: data.sendPhone,
      sign: data.sign,
      time: time,
      content: data.content
    };
    orderInfoData.push(orderInfo);
    wx.setStorageSync('order', orderInfoData)
  },


  //手机号验
  removeEmptyArrayEle: function (arr) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == undefined && arr[i] == null || arr[i] == "") {
        arr.splice(i, 1);
        i = i - 1; // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位，
        // 这样才能真正去掉空元素,觉得这句可以删掉的连续为空试试，然后思考其中逻辑
      }
    }
    return arr;
  },
  //正则验证手机号
  isPoneAvailable: function (e) {
    if (e.type == 'blur') {
      var phone = e.detail.value.split("\n");
      var phones = this.removeEmptyArrayEle(phone);
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      for (var i = 0; i < phones.length; i++) {
        if (!myreg.test(phones[i])) {
          wx.showToast({
            title: '手机号格式不正确',
            icon: 'none',
            duration: 2000,
            mask: true
          })
        }
      }
      this.setData({
        sendPhone: phones
      })
    }
  },

  //短信内容的实时数量
  signaNum: function (e) {
    var num = e.detail.value.length;
    this.setData({
      signaNum: num
    })
  },
  textNum: function (e) {
    var upd_num = e.detail.value.length;
    var page_upd_num = Math.ceil(upd_num / this.data.sms_num);
    this.setData({
      cont_num: upd_num + 2,
      page_num: page_upd_num,
    })
  },
  //获取openid
  getUserOpenId: function (url) {
    let that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: url,
            method: "post",
            data: {
              code: res.code
            },
            success: function (res) {
              if (res.data.code == '200') {
                that.setData({
                  userId: res.data.data.openId
                })
                wx.hideNavigationBarLoading();
              } else {
                wx.showToast({
                  title: '网络超时',
                  icon: 'loading',
                  duration: 1500
                })
                var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId'
                that.getUserOpenId(getOpenid)
              }

            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showNavigationBarLoading();
    var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId'
    this.getUserOpenId(getOpenid)
    switch (options.class) {
      case '0':
        var contData = JSON.parse(options.data);
        var contents = contData.content;
        //获取文本的数量
        var num = contents.length;
        var pag_num = Math.ceil(num / this.data.sms_num);
        this.setData({
          contData: contData,
          content: contents,
          cont_num: num + 2,
          page_num: pag_num,
          classId: options.class
        })
        break;
      case '1':
        var contData = JSON.parse(options.data);
        //获取文本的数量
        var num = contData.length;
        var pag_num = Math.ceil(num / this.data.sms_num);
        this.setData({
          content: contData,
          cont_num: num + 2,
          page_num: pag_num,
          classId: options.class
        })
        break;
    }

  },
  //第一次提交
  onSubmit: function (e) {
    if (e.type == 'submit') {
      var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
      if (e.detail.value.phone == '') {
        wx.showToast({
          title: '请输入正确的手机号',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      if (e.detail.value.signature == '') {
        wx.showToast({
          title: '输入3-8个字符的短信签名',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      if (e.detail.value.content == '') {
        wx.showToast({
          title: '请输入短信内容',
          icon: 'none',
          duration: 2000,
          mask: true
        })
        return false;
      };
      switch (e.detail.target.dataset.status) {
        case '1':
          this.setData({
            showCenterDialog: !this.data.showCenterDialog,
            showDialog: !this.data.showDialog,
            upContent: e.detail.value.content,
            signature: e.detail.value.signature,
            sendPhone: e.detail.value.phone
          });
          break;
      }
    }
  },
  //电话热线
  onMakePhone: function (e) {
    wx.makePhoneCall({
      phoneNumber: '400-716-3021',
    })
  },
})